package cn.mysdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName:
 * @Description:
 * @Author: SDP
 * @Date: 2020-10-30
 * Table:
 * Comment:
 */
@Slf4j
public class FileUtil {

    public static Map<String, String> fileDateMap = new HashMap<>();
    public static Map<String, String> fileAuthMap = new HashMap<>();
    public static Map<String, String> fileOldMap = new HashMap<>();

    public static void clear() {
        fileDateMap = new HashMap<>();
        fileAuthMap = new HashMap<>();
        fileOldMap = new HashMap<>();
    }

    public static void addOld(String name, String prop, String tsp) {
        fileOldMap.put(name+";"+prop, tsp);
    }

    public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static String getOld(String name, String prop, String defaultValue) {
        String tsp = fileOldMap.get(name + ";" + prop);
        if (!StringUtils.isEmpty(tsp)) {
            return tsp.trim();
        }
        if ("* @Date:".equals(prop)) {
            return dateFormat.format(new Date());
        } else {
            return defaultValue;
        }
    }

    public static boolean hasOld(String name, String prop) {
        String tsp = fileOldMap.get(name + ";"+prop);
        if (!StringUtils.isEmpty(tsp)) {
            return true;
        }
        return false;
    }

    public static void fetchFileOldProperty(File file) throws IOException {
        if (!file.exists()) {
            return;
        }
        FileInputStream fis = null;
        InputStreamReader read = null;
        BufferedReader bufferedReader = null;
        try {
            fis = new FileInputStream(file);
            read = new InputStreamReader(fis, "utf-8");
            bufferedReader = new BufferedReader(read);
            String txt;
            String[] props = new String[]{"* @Date:", "* @Author:", "* @Version:"};

            while ((txt = bufferedReader.readLine()) != null) {
                txt = txt.trim();
                for (String prop : props) {
                    if (txt.startsWith(prop)) {
                        FileUtil.addOld(file.getAbsolutePath(), prop, txt.replace(prop, ""));
                        break;
                    }
                }
            }
            bufferedReader.close();
            bufferedReader = null;
            read.close();
            read = null;
            fis.close();
            fis = null;

        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (read != null) {
                read.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }

    public static String callCmd(String locationCmd) throws IOException {
        StringBuilder sb = new StringBuilder();
        try {
            String[] locationCmds = locationCmd.split("\n");
            Process child = Runtime.getRuntime().exec(locationCmds);
            InputStream in = child.getInputStream();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(in));
            String line;
            while((line=bufferedReader.readLine())!=null)
            {
                if(line.contains("%") && line.contains("Total") && line.contains("Average")) {
                } else if (line.contains("Dload") && line.contains("Total") && line.contains("Upload")) {
                } else {
                    sb.append(line + "\n");
                }
            }
            in.close();
            if(sb.length() == 0) {
                in = child.getErrorStream();
                bufferedReader=new BufferedReader(new InputStreamReader(in));
                while((line=bufferedReader.readLine())!=null)
                {
                    if(line.contains("%") && line.contains("Total") && line.contains("Average")) {
                    } else if (line.contains("Dload") && line.contains("Total") && line.contains("Upload")) {
                    } else {
                        sb.append(line + "\n");
                    }
                }

                in.close();
            }

            try {
                child.waitFor();
            } catch (InterruptedException e) {
                log.info("219，{}", e.getMessage(), e);
            }
            return sb.toString();
        } catch (IOException e) {
            log.error("{}", e.getMessage(), e);

            throw e;
        }
    }

    public static String callCmdWithStdin(String locationCmd, String stdinStr) throws Exception {
        String result = "";
        // 要运行的系统命令及其参数
        String[] command = locationCmd.split("\n");

        // 要替换标准输入的字符串
        String inputString = stdinStr;

        // 创建ProcessBuilder对象
        ProcessBuilder processBuilder = new ProcessBuilder(command);

        try {
            // 启动进程
            Process process = processBuilder.start();

            // 获取标准输入流
            OutputStream stdin = process.getOutputStream();

            // 将字符串写入标准输入流
            stdin.write(inputString.getBytes());
            stdin.flush();
            stdin.close();

            // 获取标准输出流
            BufferedReader stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));

            // 读取标准输出
            String line;
            StringBuilder out = new StringBuilder();
            StringBuilder outDetail = new StringBuilder();
            while ((line = stdout.readLine()) != null) {
                out.append(line);
                out.append("\n");
                outDetail.append(line.length()+":"+line+";\n");
            }
            System.out.println("out:");
            System.out.println(out.toString());
            System.out.println("outDetail:");
            System.out.println(outDetail.toString());

            // 获取标准错误流
            BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            StringBuilder err = new StringBuilder();
            StringBuilder errDetail = new StringBuilder();
            // 读取标准错误
            while ((line = stderr.readLine()) != null) {
                boolean hasMore = false;
                for(int i = 0; i < line.length();i++) {
                    String c = line.substring(i, i+1);
                    if(c.charAt(0) <= 27 || !StringUtils.hasText(c) || "[]?125lhKG⠙ ⠹ ⠸ ⠸ ⠴ ⠦ ⠧ ⠇ ⠏ ⠋ ⠙ ⠹ ⠸ ⠼ ⠼ ⠦ ⠧ ⠇ ⠏ ⠋ ⠙ ⠙ ⠸ ⠼ ⠴ ⠴ ⠧ ⠧ ⠏ ⠋ ⠋ ⠹ ⠸ ⠼ ⠼ ⠦ ⠦ ⠇ ⠇ ⠏ ⠙ ⠹ ⠸ ⠸ ⠴ ⠦ ⠧ ".contains(c)) {
                        continue;
                    }
                    hasMore = true;
                    break;
                }
                if(hasMore) {
                    err.append(line);
                    err.append("\n");
                }
                errDetail.append(line.length()+":"+line+";\n");
            }
            System.err.println("err:");
            System.err.println(err.toString());
            System.err.println("errDetail:");
            System.err.println(errDetail.toString());

            // 等待进程完成并获取退出码
            int exitCode = process.waitFor();
            System.out.println("Process exited with code " + exitCode);

            result = out.toString();

        } catch (Exception ex) {
            throw ex;
        }
        return result;
    }
}
